package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"rpc/model/mysql"
	"rpc/model/redis"
	"rpc/pkg"
	"strconv"

	"rpc/bili"
	"rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *bili.CreateOrderRequest) (*bili.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Where("id=?", in.UserId).Limit(1).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}
	//生成唯一订单号
	num := uuid.NewString()
	price := in.Price - 8
	order := mysql.Order{
		UserId:  int(in.UserId),
		Pride:   float64(price),
		OrderSn: num,
		PayType: int8(in.PayType),
	}
	err := order.CreateOrder()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}
	m := mysql.User{
		Level:   2,
		Amount:  9999,
		Times:   86400,
		Checked: 1,
	}
	err = m.CreateUser()
	if err != nil {
		return nil, fmt.Errorf("会员信息生成失败")
	}

	redis.SyncUser(&m)
	redis.SyncLevel(int(m.ID), m.Level)
	s := fmt.Sprintf("%.2f", order.Pride)
	if redis.IsNull(int(m.ID)) == "0" {
		return nil, fmt.Errorf("会员已过期")
	}
	Url := pkg.AliPay(strconv.FormatInt(in.UserId, 10), num, s)
	return &bili.CreateOrderResponse{Url: Url}, nil
}
